package com.chucang.shucang.pms.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chucang.shucang.common.base.page.PageData;
import com.chucang.shucang.common.base.utils.R;
import com.chucang.shucang.common.security.annotation.Inner;
import com.chucang.shucang.pms.constant.PmsCommonConstant;
import com.chucang.shucang.pms.entity.CollectionBaseEntity;
import com.chucang.shucang.pms.entity.CollectionMallEntity;
import com.chucang.shucang.pms.feign.vo.UserCollectionHoldEntity;
import com.chucang.shucang.pms.service.CollectionBaseService;
import com.chucang.shucang.pms.service.CollectionMallService;
import com.chucang.shucang.pms.vo.CollectionMallPageResVO;
import com.chucang.shucang.pms.vo.CollectionOnSaleDetailResVO;
import com.chucang.shucang.pms.vo.CollectionOnSalePageResVO;
import com.chucang.shucang.pms.vo.query.CollectionMallQuery;
import com.chucang.shucang.pms.vo.query.CollectionOnSaleQuery;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 藏品商城表
 *
 * @author flitsneak flitsneak@gmail.com
 * @since 1.0.0 2022-09-12
 */
@RestController
@RequestMapping("/collectionmall")
@RequiredArgsConstructor
@Api(tags = "藏品商城表")
public class CollectionMallController {

    private final CollectionMallService collectionMallService;

    private final CollectionBaseService collectionBaseService;

    private final ThreadPoolTaskExecutor pmsExecutor;

    /**
     * 藏品商城分页
     *
     * @param collectionMallQuery c
     * @return r
     */
    @Cacheable(value = "collectionMallPage", key = "{#collectionMallQuery.page}", unless = "#collectionMallQuery.fuzzy!=null")
    @PostMapping("/collectionMallPage")
    public R<PageData<CollectionMallPageResVO>> collectionMallPage(@Valid @RequestBody CollectionMallQuery collectionMallQuery) {
        //分页查询藏品数据
        PageData<CollectionBaseEntity> baseEntityPageData = collectionBaseService.collectionBasePage(collectionMallQuery);
        HashMap<Long, String> stringHashMap = new HashMap<>(16);
        HashMap<Long, BigDecimal> priceMap = new HashMap<>(16);
        HashMap<Long, String> coverPicMap = new HashMap<>(16);
        baseEntityPageData.getList().forEach(v -> {
            stringHashMap.put(v.getId(), v.getDcName());
            priceMap.put(v.getId(), v.getDcPrice());
            coverPicMap.put(v.getId(), v.getCoverPicture());
        });
        //查询商品最低价
        List<CollectionMallPageResVO> pageResVOSList = baseEntityPageData
                .getList()
                .stream()
                .map(c -> CompletableFuture.supplyAsync(() -> collectionMallService.getTheBottomPrice(c.getId()), pmsExecutor))
                .collect(Collectors.toList())
                .stream()
                .map(CompletableFuture::join)
                .filter(Objects::nonNull)
                .collect(Collectors.toList())
                .stream()
                .map(d -> {
                    CollectionMallPageResVO mallPageResVO = new CollectionMallPageResVO();
                    mallPageResVO.setDcName(stringHashMap.get(d.getCollectionId()));
                    mallPageResVO.setBottomPrice(d.getSellingPrice());
                    mallPageResVO.setCoverPicture(coverPicMap.get(d.getCollectionId()));
                    mallPageResVO.setId(d.getCollectionId());
                    stringHashMap.remove(d.getCollectionId());
                    return mallPageResVO;
                })
                .collect(Collectors.toList());
        //空商品 默认最低价为发售价
        ArrayList<CollectionMallPageResVO> resVOArrayList = new ArrayList<>(16);
        if (!CollUtil.isEmpty(stringHashMap)) {
            stringHashMap.forEach((k, v) -> {
                CollectionMallPageResVO mallPageResVO = new CollectionMallPageResVO();
                mallPageResVO.setDcName(v);
                mallPageResVO.setBottomPrice(priceMap.get(k));
                mallPageResVO.setCoverPicture(coverPicMap.get(k));
                mallPageResVO.setId(k);
                resVOArrayList.add(mallPageResVO);
            });
        }
        //链表合并
        pageResVOSList.addAll(resVOArrayList);
        PageData<CollectionMallPageResVO> resVOPageData = new PageData<>(pageResVOSList, baseEntityPageData.getTotal());

        return R.ok(resVOPageData);
    }

    /**
     * 在售商品信息分页
     *
     * @param collectionOnSaleQuery coq
     * @return r
     */
    @PostMapping("/onSaleCollectionPage")
    public R<CollectionOnSalePageResVO> onSaleCollectionPage(@Valid @RequestBody CollectionOnSaleQuery collectionOnSaleQuery) {
        CollectionOnSalePageResVO onSaleCollectionPage = collectionMallService.onSaleCollectionPage(collectionOnSaleQuery);
        return R.ok(onSaleCollectionPage);
    }

    /**
     * 在售商品详情
     *
     * @param id 在售藏品id
     * @return r
     */
    @GetMapping("/getOnSaleCollectionDetail/{id}")
    public R<CollectionOnSaleDetailResVO> getOnSaleCollectionDetail(@PathVariable Long id) {
        CollectionOnSaleDetailResVO collectionOnSaleDetailResVO = collectionMallService.getOnSaleCollectionDetail(id);
        return R.ok(collectionOnSaleDetailResVO);
    }

    /**
     * 藏品上架商城
     *
     * @param userCollectionHoldList uch
     * @return r
     */
    @Inner
    @PostMapping("/collectionsOnConsign")
    public R<String> collectionsOnConsign(@RequestBody List<UserCollectionHoldEntity> userCollectionHoldList) {
        if (collectionMallService.collectionsOnConsign(userCollectionHoldList)) {
            return R.ok();
        }
        return R.failed();
    }

    /**
     * 撤销藏品寄售
     *
     * @param id 主键id
     * @return r
     */
    @Inner
    @GetMapping("/withdrawCollectionConsign/{id}")
    public R<String> withdrawCollectionConsign(@PathVariable Long id) {
        LambdaUpdateWrapper<CollectionMallEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(CollectionMallEntity::getId, id)
                .set(CollectionMallEntity::getStatus, PmsCommonConstant.COLLECTION_WITHDRAW);
        if (collectionMallService.update(updateWrapper)) {
            return R.ok();
        }
        return R.failed();
    }

    @Inner
    @GetMapping("/lockCollectionStock/{id}/{userId}")
    public R<CollectionMallEntity> lockCollectionStock(@PathVariable Long id, @PathVariable Long userId) {
        CollectionMallEntity byId = collectionMallService.getById(id);
        if (Objects.equals(byId.getSellerId(), userId)) {
            //本人不能买本人藏品
            return R.failed();
        }
        //库存锁定失败
        if (!byId.getStatus().equals(PmsCommonConstant.COLLECTION_CONSIGN)) {
            return R.failed();
        }
        //锁定库存
        LambdaUpdateWrapper<CollectionMallEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CollectionMallEntity::getId, id)
                .set(CollectionMallEntity::getStatus, PmsCommonConstant.COLLECTION_LOCKED);
        collectionMallService.update(updateWrapper);
        return R.ok(byId);
    }

    @Inner
    @GetMapping("/unlockCollectionStock/{id}")
    public R<String> unlockCollectionStock(@PathVariable Long id) {
        CollectionMallEntity byId = collectionMallService.getById(id);
        //库存锁定失败
        if (!byId.getStatus().equals(PmsCommonConstant.COLLECTION_LOCKED)) {
            return R.failed();
        }
        //锁定库存
        LambdaUpdateWrapper<CollectionMallEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CollectionMallEntity::getId, id)
                .set(CollectionMallEntity::getStatus, PmsCommonConstant.COLLECTION_CONSIGN);
        collectionMallService.update(updateWrapper);
        return R.ok();
    }

}